package com.kb.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.collect.Lists;
import com.kb.common.ApiResponse;
import com.kb.common.MeException;
import com.kb.domain.ComponentInfo;
import com.kb.dto.gc.ComponentDataDTO;
import com.kb.dto.gc.TemplateFields;
import com.kb.entity.ModelApplication;
import com.kb.service.CallbackNotificationService;
import com.kb.service.ComponentDataService;
import com.kb.service.ViewPreviewDataService;
import com.kb.service.gc.CreateModeService;
import com.kb.util.GCutil;
import com.kb.util.MessageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/business")
@Api(value = "国创元器件", tags = {"国创元器件"})
@Slf4j
/**
 * 国创元器件
 */
public class BusinessController {

    @Resource
    private ComponentDataService componentDataService;
    @Resource
    private CallbackNotificationService callbackNotificationService;
    @Resource
    private CreateModeService createModeService;
    @Resource
    private ViewPreviewDataService viewPreviewDataService;
    /**
     * 建模
     */
    @PostMapping("/createMode")
    @ResponseBody
    @ApiOperation("建模")
    public ApiResponse<?> createMode(@RequestBody List<ComponentDataDTO> list) throws MeException {
        createModeService.createMode(list);
        return ApiResponse.success("成功");
    }
    /**
     * 新增元器件
     */
    @PostMapping("/createComponents")
    @ResponseBody
    @ApiOperation("新增元器件")
    public ApiResponse<?> createComponents(@RequestBody TemplateFields templateFieldBean) throws MeException {
        ComponentDataDTO componentDataDTO = new ComponentDataDTO();
        componentDataDTO.setTemplateFieldBean(templateFieldBean);
        componentDataDTO.setPartNumber(templateFieldBean.getKey0());
        List<ComponentDataDTO> list = Lists.newArrayList(componentDataDTO);
        createModeService.createMode(list);
        return ApiResponse.success("成功");
    }

    /**
     * 获取物料数据
     * @param number 型号
     * @return
     * @throws MeException
     */
    @GetMapping("/getComponent")
    @ResponseBody
    @ApiOperation("获取物料数据")
    public ApiResponse<?> getComponent(String number) throws MeException {
        Map component = componentDataService.getComponent(number);
        if (Objects.isNull(component)){
            return ApiResponse.success(null);
        }
        return ApiResponse.successCount(component.get("list"),component.get("total"));
    }

    /**
     * 型号预览
     *
     * @param number 型号
     * @return
     */
    @GetMapping("/viewPreview")
    @ApiOperation("型号预览")
    public String viewPreview(String number,String source) {
        try {
            String viewed = componentDataService.viewPreview(number);
            if (Objects.isNull(viewed)) {
                return "404";
            }
            //加入调用统计
            viewPreviewDataService.recordCallNumber(number,source);
            //加入免登 请求获取token 优化: 分账号密码,让用户传账号密码和系统唯一标识进来(比如PLM系统就叫PLM)进来,通过获取token 看账号密码
            String authorizationToken = GCutil.getLocalGcToken();
            return "redirect:http://192.168.10.185/component/detail/" + viewed + "?token=" + authorizationToken;
//            return "redirect:http://192.168.10.185/component/detail/" + viewed;
        } catch (MeException e) {
            throw new RuntimeException(e);
        }
    }
    @GetMapping("/getHome")
    @ApiOperation("型号预览")
    public String getHome(String number) {
        try {
            //加入免登 请求获取token 优化: 分账号密码,让用户传账号密码和系统唯一标识进来(比如PLM系统就叫PLM)进来,通过获取token 看账号密码
            String authorizationToken = GCutil.getLocalGcToken();
            return "redirect:http://192.168.10.185/component?token=" + authorizationToken;
        } catch (MeException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping(value = "/toModelApplication",method = RequestMethod.GET)
    public String toPage(HttpServletRequest request){
        return request.getParameter("url");
    }

    /**
     * 输入型号，跳转预览页面
     * @param keyWords 型号
     * @return
     * @throws MeException
     */
    @GetMapping("/search")
    @ApiOperation("查询")
    public String search(String keyWords) throws MeException {
        return  "redirect:http://192.168.10.185/component/search?keyWords=" + keyWords;
    }
    /**
     * 文件预览
     *
     * @param url
     * @return
     */
    @GetMapping("/filePreview")
    public String filePreview(String url) {
        return "redirect:http://192.168.10.33:8012/onlinePreview?url=" + Base64.encode(url);
    }

    /**
     * 根据型号获取信息
     */
    @ResponseBody
    @PostMapping("/getInfoByPartNumber")
    @ApiOperation("根据型号获取信息")
    public ApiResponse<List<ComponentInfo>> getInfoByPartNumber(@RequestBody ModelApplication modelApplication) throws MeException {
        return ApiResponse.success(componentDataService.getInfoByPartNumber(modelApplication));
    }


    /**
     * 根据型号查询id
     * 数据插入到通知表中
     */
    @ResponseBody
    @Deprecated
    @GetMapping("/dataSyn")
    public ApiResponse dataSyn() throws MeException, InterruptedException {
        // 指定要读取的 Excel 文件
        File file = new File("D:\\数据库文档\\data_syn.xlsx"); // 请替换为实际文件路径
        // 创建 ExcelReader
        ExcelReader reader = ExcelUtil.getReader(file);

        // 读取数据到 Map 中
        List<Map> mapList = reader.readAll(Map.class);

        // 遍历输出每行数据的 Map
        List<List<Map>> listList = Lists.partition(mapList, 40);
        for (List<Map> maps : listList) {
            for (Map rowMap : maps) {
                ModelApplication modelApplication = new ModelApplication();

                modelApplication.setPartNumber(rowMap.get("part_number").toString());
                modelApplication.setType(2);
                if (Objects.nonNull(rowMap.get("organization_name"))) {
                    modelApplication.setOrgName(rowMap.get("organization_name").toString());
                }
                modelApplication.setCreateBy("chenzhixiang");
                componentDataService.partNumber2Id(modelApplication);
            }

        }
        // 关闭 Reader
        reader.close();
        return ApiResponse.success("数据初始化成功");
    }

    /**
     * 读取Excel数据同步
     */
    @ResponseBody
    @GetMapping("/dataSyn2")
    public ApiResponse dataSyn2() throws MeException, InterruptedException {
        // 指定要读取的 Excel 文件
        File file = new File("D:\\数据库文档\\data_syn2.xlsx"); // 请替换为实际文件路径

        // 创建 ExcelReader
        ExcelReader reader = ExcelUtil.getReader(file);

        // 读取数据到 Map 中
        List<Map> mapList = reader.readAll(Map.class);
        int i = 0;
        // 遍历输出每行数据的 Map
        List<List<Map>> listList = Lists.partition(mapList, 40);
        for (List<Map> maps : listList) {
            for (Map rowMap : maps) {
                ModelApplication modelApplication = new ModelApplication();

                modelApplication.setPartNumber(rowMap.get("part_number").toString());
                log.info(rowMap.get("part_number").toString());
                modelApplication.setType(2);
                if (Objects.nonNull(rowMap.get("organization_name"))) {
                    modelApplication.setOrgName(rowMap.get("organization_name").toString());
                }
                componentDataService.getInfoByPartNumber(modelApplication);
                i++;
                log.info("dataSyn2============================：" + i);
//                Thread.sleep(300);
            }
            System.out.println("-----------------------------------");
        }

        // 关闭 Reader
        reader.close();
        MessageUtil.sentMessage("23988", "同步结束"+i,"国创资源库");
        return ApiResponse.success("同步成功");
    }


    /**
     * es数据更新
     */
    @ResponseBody
    @GetMapping("/updateESData")
    public void test() throws MeException, InterruptedException {
        // 指定要读取的 Excel 文件
        File file = new File("D:\\数据库文档\\esData.xlsx"); // 请替换为实际文件路径

        // 创建 ExcelReader
        ExcelReader reader = ExcelUtil.getReader(file);

        // 读取数据到 Map 中
        List<Map> mapList = reader.readAll(Map.class);

        // 遍历输出每行数据的 Map
        List<List<Map>> listList = Lists.partition(mapList, 10); //10个一组
        for (List<Map> maps : listList) {
            List<String> idList = maps.stream()
                    .map(map -> map.get("id"))
                    .filter(Objects::nonNull)
                    .map(Object::toString)
                    .collect(Collectors.toList());
            System.out.println(JSONUtil.toJsonStr(idList));
            componentDataService.updateESData(idList);
        }
//        Thread.sleep(3000);
        // 关闭 Reader
        reader.close();
    }
}
